﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '员工为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" @change="onPersonSelected" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ApplyDate_FormItem"
								prop="Entity.ApplyDate"
								:rules="[{ required: true, message: '申请日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="申请日期" tooltip="申请日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ApplyDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EffectiveDate_FormItem"
								prop="Entity.EffectiveDate"
								:rules="[{ required: true, message: '生效日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="生效日期" tooltip="变更生效日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.EffectiveDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_TransferType_FormItem"
								prop="Entity.TransferType"
								:rules="[{ required: true, message: '调整类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="调整类型" tooltip="调整类型" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.TransferType" clearable class="width100" @change="onTransferTypeChange">
									<el-option v-for="item in TRANSFER_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_TransferReason_FormItem" prop="Entity.TransferReason">
								<template #label>
									<WtmLabelTooltip label="调整原因" tooltip="调整原因" />
								</template>
								<el-input type="textarea" v-model="stateData.vmModel.Entity.TransferReason" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="SupportingDocumentId_FormItem" prop="Entity.SupportingDocumentId">
								<template #label>
									<WtmLabelTooltip label="证明文件" tooltip="人事上传证明文件信息" />
								</template>
								<wtm-upload-file
									v-model="stateData.vmModel.Entity.SupportingDocumentId"
									:allowed-types="['application/pdf', 'image/jpeg', 'image/png', 'image/jpg']"
									clearable
									:multi="false"
								></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section" v-show="stateData.vmModel.Entity.TransferType !== null">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>原职位信息</span>
						<el-tag v-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.SALARY" size="small" type="info" style="margin-left: 10px">
							仅薪资信息
						</el-tag>
						<el-tag
							v-else-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.POSITION"
							size="small"
							type="warning"
							style="margin-left: 10px"
						>
							仅岗位信息
						</el-tag>
						<el-tag v-else-if="stateData.vmModel.Entity.TransferType !== null" size="small" type="success" style="margin-left: 10px">
							岗位和薪资信息
						</el-tag>
					</div>
					<WtmDeptSelector
						v-show="showPositionFields"
						v-model="stateData.vmModel.Entity.OriginalGroupId"
						prop="Entity.OriginalGroupId"
						label="原部门"
						:auth="false"
						:rules="showPositionFields ? [{ required: true, message: '请选择原部门', trigger: 'change' }] : []"
						:positionRules="showPositionFields ? [{ required: true, message: '请选择原岗位', trigger: 'change' }] : []"
						:show-position="true"
						position-label="原岗位"
						position-prop="Entity.OriginalPositionId"
						v-model:position-id="stateData.vmModel.Entity.OriginalPositionId"
						@position-change="onOriginalPositionChange"
						:use-row="true"
						:dept-col="12"
						:position-col="12"
					/>
					<el-row :gutter="20">
						<el-col v-show="showRankFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalRank_FormItem" prop="Entity.OriginalRank">
								<template #label>
									<WtmLabelTooltip label="原职级" tooltip="原职级" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.OriginalRank" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col v-show="showSalaryFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalBaseSalary_FormItem" prop="Entity.OriginalBaseSalary">
								<template #label>
									<WtmLabelTooltip label="原基本薪资" tooltip="原基本薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.OriginalBaseSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col v-show="showSalaryFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalPositionSalary_FormItem" prop="Entity.OriginalPositionSalary">
								<template #label>
									<WtmLabelTooltip label="原岗位薪资" tooltip="原岗位薪资" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.OriginalPositionSalary"
									clearable
									class="width100"
									:disabled="originalSalaryFieldsDisabled"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col v-show="showSalaryFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalPerformanceSalary_FormItem" prop="Entity.OriginalPerformanceSalary">
								<template #label>
									<WtmLabelTooltip label="原绩效薪资" tooltip="原绩效薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.OriginalPerformanceSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section" v-show="stateData.vmModel.Entity.TransferType !== null">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>调整后信息</span>
						<el-tag v-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.SALARY" size="small" type="info" style="margin-left: 10px">
							仅薪资信息
						</el-tag>
						<el-tag
							v-else-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.POSITION"
							size="small"
							type="warning"
							style="margin-left: 10px"
						>
							仅岗位信息
						</el-tag>
						<el-tag v-else-if="stateData.vmModel.Entity.TransferType !== null" size="small" type="success" style="margin-left: 10px">
							岗位和薪资信息
						</el-tag>
					</div>

					<WtmDeptSelector
						v-show="showPositionFields"
						v-model="stateData.vmModel.Entity.NewGroupId"
						prop="Entity.NewGroupId"
						label="新部门"
						:auth="false"
						:rules="showPositionFields ? [{ required: true, message: '请选择新部门', trigger: 'change' }] : []"
						:positionRules="showPositionFields ? [{ required: true, message: '请选择新岗位', trigger: 'change' }] : []"
						:show-position="true"
						position-label="新岗位"
						position-prop="Entity.NewPositionId"
						v-model:position-id="stateData.vmModel.Entity.NewPositionId"
						@position-change="onNewPositionChange"
						:use-row="true"
						:dept-col="12"
						:position-col="12"
					/>

					<el-row :gutter="20">
						<el-col v-show="showRankFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewRank_FormItem" prop="Entity.NewRank">
								<template #label>
									<WtmLabelTooltip label="新职级" tooltip="新职级" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.NewRank" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col v-show="showSalaryFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewBaseSalary_FormItem" prop="Entity.NewBaseSalary">
								<template #label>
									<WtmLabelTooltip label="新基本薪资" tooltip="新基本薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.NewBaseSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col v-show="showSalaryFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewPositionSalary_FormItem" prop="Entity.NewPositionSalary">
								<template #label>
									<WtmLabelTooltip label="新岗位薪资" tooltip="新岗位薪资" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.NewPositionSalary"
									clearable
									class="width100"
									:disabled="salaryFieldsDisabled"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col v-show="showSalaryFields" :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewPerformanceSalary_FormItem" prop="Entity.NewPerformanceSalary">
								<template #label>
									<WtmLabelTooltip label="新绩效薪资" tooltip="新绩效薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.NewPerformanceSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="false"
								:disabled="true"
								placeholder="选取人员后带入"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrTransferRequestBillApi as api } from '/@/views/hr/syshrtransferrequestbill/api';
import other from '/@/utils/other';
import { ISysHrTransferRequestBillVm } from '/@/views/hr/syshrtransferrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { useUserInfo } from '/@/stores/userInfo';
import { getCurrentUserMainGroupId } from '/@/utils/userGroup';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
} as const;

const TRANSFER_TYPE_OPTIONS = [
	{ value: '岗位调整', label: '岗位调整' },
	{ value: '薪资调整', label: '薪资调整' },
	{ value: '岗位和薪资调整', label: '岗位和薪资调整' },
	{ value: '晋升', label: '晋升' },
	{ value: '降级', label: '降级' },
] as const;

// 调整类型常量
const TRANSFER_TYPE = {
	POSITION: '岗位调整',
	SALARY: '薪资调整',
	BOTH: '岗位和薪资调整',
	PROMOTION: '晋升',
	DEMOTION: '降级',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

// 获取用户信息store
const userInfoStore = useUserInfo();

// 动态表单验证规则
const formRules = computed(() => {
	const rules: Record<string, any[]> = {
		'Entity.PersonId': [{ required: true, message: '请选择员工', trigger: 'change' }],
		'Entity.ApplyDate': [{ required: true, message: '请选择申请日期', trigger: 'change' }],
		'Entity.EffectiveDate': [{ required: true, message: '请选择生效日期', trigger: 'change' }],
		'Entity.TransferType': [{ required: true, message: '请选择调整类型', trigger: 'change' }],
		'Entity.GroupId': [{ required: true, message: '请选择所属部门', trigger: 'change' }],
		'Entity.OrgId': [{ required: true, message: '请选择公司', trigger: 'change' }],
	};

	// 根据调整类型动态添加验证规则
	if (showPositionFields.value) {
		rules['Entity.OriginalGroupId'] = [{ required: true, message: '请选择原部门', trigger: 'change' }];
		rules['Entity.NewGroupId'] = [{ required: true, message: '请选择新部门', trigger: 'change' }];
		rules['Entity.OriginalPositionId'] = [{ required: true, message: '请选择原岗位', trigger: 'change' }];
		rules['Entity.NewPositionId'] = [{ required: true, message: '请选择新岗位', trigger: 'change' }];
	}

	if (showRankFields.value) {
		rules['Entity.OriginalRank'] = [{ required: true, message: '请输入原职级', trigger: 'blur' }];
		rules['Entity.NewRank'] = [{ required: true, message: '请输入新职级', trigger: 'blur' }];
	}

	if (showSalaryFields.value) {
		rules['Entity.OriginalBaseSalary'] = [{ required: true, message: '请输入原基本薪资', trigger: 'blur' }];
		rules['Entity.NewBaseSalary'] = [{ required: true, message: '请输入新基本薪资', trigger: 'blur' }];
		rules['Entity.OriginalPositionSalary'] = [{ required: true, message: '请输入原岗位薪资', trigger: 'blur' }];
		rules['Entity.NewPositionSalary'] = [{ required: true, message: '请输入新岗位薪资', trigger: 'blur' }];
		rules['Entity.OriginalPerformanceSalary'] = [{ required: true, message: '请输入原绩效薪资', trigger: 'blur' }];
		rules['Entity.NewPerformanceSalary'] = [{ required: true, message: '请输入新绩效薪资', trigger: 'blur' }];
	}

	return rules;
});

const stateData = reactive<IViewModel<ISysHrTransferRequestBillVm>>({
	vmModel: {
		Entity: {
			PersonId: null,
			ApplyDate: null,
			EffectiveDate: null,
			TransferType: null,
			OrgId: null,
			OriginalGroupId: null,
			OriginalPositionId: null,
			OriginalRank: null,
			OriginalBaseSalary: null,
			OriginalPositionSalary: null,
			OriginalPerformanceSalary: null,
			NewGroupId: null,
			NewPositionId: null,
			NewRank: null,
			NewBaseSalary: null,
			NewPositionSalary: null,
			NewPerformanceSalary: null,
			TransferReason: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			ApprovalOpinion: null,
			StaffNo: null,
			Name: null,
			SupportingDocumentId: [],
		},
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},

	AllSysPersons: [] as any[],
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const canSubmit = computed(() => hasEntityId.value && hasSavedOnce.value);

// 根据调整类型控制字段显示
const showPositionFields = computed(() => {
	const transferType = stateData.vmModel.Entity.TransferType;
	return (
		transferType === TRANSFER_TYPE.POSITION ||
		transferType === TRANSFER_TYPE.BOTH ||
		transferType === TRANSFER_TYPE.PROMOTION ||
		transferType === TRANSFER_TYPE.DEMOTION
	);
});

const showSalaryFields = computed(() => {
	const transferType = stateData.vmModel.Entity.TransferType;
	return (
		transferType === TRANSFER_TYPE.SALARY ||
		transferType === TRANSFER_TYPE.BOTH ||
		transferType === TRANSFER_TYPE.PROMOTION ||
		transferType === TRANSFER_TYPE.DEMOTION
	);
});

const showRankFields = computed(() => {
	const transferType = stateData.vmModel.Entity.TransferType;
	return (
		transferType === TRANSFER_TYPE.POSITION ||
		transferType === TRANSFER_TYPE.BOTH ||
		transferType === TRANSFER_TYPE.PROMOTION ||
		transferType === TRANSFER_TYPE.DEMOTION
	);
});

// 原岗位薪资字段是否禁用（选择原岗位后禁用）
const originalSalaryFieldsDisabled = computed(() => {
	// 当显示薪资字段且选择了原岗位时，禁用薪资输入
	return showSalaryFields.value && !!stateData.vmModel.Entity.OriginalPositionId;
});

// 新岗位薪资字段是否禁用（选择新岗位后禁用）
const salaryFieldsDisabled = computed(() => {
	// 当显示薪资字段且选择了新岗位时，禁用薪资输入
	return showSalaryFields.value && !!stateData.vmModel.Entity.NewPositionId;
});

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗，更新实体ID
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
		hasSavedOnce.value = true;
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleSuccess(response, isSubmit))
			.catch(handleError);
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false // 保存后不关闭弹窗
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true // 提交后关闭弹窗
	);
};

// 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = '';
		stateData.vmModel.Entity.Name = '';
		stateData.vmModel.Entity.OrgId = '';
		stateData.vmModel.Entity.GroupId = '';
	}
};

// 原岗位变化处理 - 自动填充原岗位薪资信息
const onOriginalPositionChange = (positionId: string | number | null, position: any) => {
	console.log('原岗位变化:', { positionId, position });
	if (positionId && position && showSalaryFields.value) {
		// 从岗位数据中获取薪资信息并填充到原岗位薪资字段
		// API返回的岗位数据中薪资字段为 Salary
		stateData.vmModel.Entity.OriginalPositionSalary = position.Salary || null;
		// 如果有其他薪资字段，也可以在此处理
		// stateData.vmModel.Entity.OriginalBaseSalary = position.BaseSalary || null;
		// stateData.vmModel.Entity.OriginalPerformanceSalary = position.PerformanceSalary || null;
	} else if (!positionId) {
		// 清空原岗位薪资字段
		stateData.vmModel.Entity.OriginalPositionSalary = null;
		// stateData.vmModel.Entity.OriginalBaseSalary = null;
		// stateData.vmModel.Entity.OriginalPerformanceSalary = null;
	}
};

// 新岗位变化处理 - 自动填充新岗位薪资信息
const onNewPositionChange = (positionId: string | number | null, position: any) => {
	console.log('新岗位变化:', { positionId, position });
	if (positionId && position && showSalaryFields.value) {
		// 从岗位数据中获取薪资信息并填充到新岗位薪资字段
		// API返回的岗位数据中薪资字段为 Salary
		stateData.vmModel.Entity.NewPositionSalary = position.Salary || null;
		// 如果有其他薪资字段，也可以在此处理
		// stateData.vmModel.Entity.NewBaseSalary = position.BaseSalary || null;
		// stateData.vmModel.Entity.NewPerformanceSalary = position.PerformanceSalary || null;
	} else if (!positionId) {
		// 清空新岗位薪资字段
		stateData.vmModel.Entity.NewPositionSalary = null;
		// stateData.vmModel.Entity.NewBaseSalary = null;
		// stateData.vmModel.Entity.NewPerformanceSalary = null;
	}
};

// 调整类型变化处理
const onTransferTypeChange = () => {
	const transferType = stateData.vmModel.Entity.TransferType;

	// 根据调整类型清空无关字段
	if (transferType === TRANSFER_TYPE.SALARY) {
		// 薪资调整时清空岗位相关字段
		stateData.vmModel.Entity.OriginalGroupId = null;
		stateData.vmModel.Entity.OriginalPositionId = null;
		stateData.vmModel.Entity.NewGroupId = null;
		stateData.vmModel.Entity.NewPositionId = null;
		stateData.vmModel.Entity.OriginalRank = null;
		stateData.vmModel.Entity.NewRank = null;
	} else if (transferType === TRANSFER_TYPE.POSITION) {
		// 岗位调整时清空薪资相关字段
		stateData.vmModel.Entity.OriginalBaseSalary = null;
		stateData.vmModel.Entity.OriginalPositionSalary = null;
		stateData.vmModel.Entity.OriginalPerformanceSalary = null;
		stateData.vmModel.Entity.NewBaseSalary = null;
		stateData.vmModel.Entity.NewPositionSalary = null;
		stateData.vmModel.Entity.NewPerformanceSalary = null;
	}

	// 清空表单验证状态，让新的验证规则生效
	nextTick(() => {
		formRef.value?.clearValidate();
	});
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	const [billCode] = await Promise.allSettled([api().getBillCode()]);

	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;

	// 设置默认部门为当前用户的主要部门
	if (!stateData.vmModel.Entity.GroupId) {
		stateData.vmModel.Entity.GroupId = getCurrentUserMainGroupId();
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 确保用户信息已加载
		await userInfoStore.setUserInfos();
		await loadSelectListData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
